'use client';

import { useState, useEffect } from 'react';
import { addToCart } from '@/lib/cart';
import { useCart } from '@/contexts/CartContext';
import Snackbar from './Snackbar';

interface Product {
  id: number;
  name: string;
  price: number;
  description?: string;
  image?: string;
  stock: number;
}

interface ProductListProps {
  sessionId: string;
}

export default function ProductList({ sessionId }: ProductListProps) {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [snackbar, setSnackbar] = useState({
    isVisible: false,
    message: '',
    type: 'success' as 'success' | 'error',
  });
  const { refreshCart } = useCart();

  useEffect(() => {
    fetchProducts();
  }, []);

  const fetchProducts = async () => {
    try {
      const response = await fetch('/api/products');
      if (response.ok) {
        const data = await response.json();
        setProducts(data);
      }
    } catch (error) {
      console.error('Failed to fetch products:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleAddToCart = async (productId: number) => {
    try {
      await addToCart(productId, 1, sessionId);
      await refreshCart(); // 刷新购物车状态
      setSnackbar({
        isVisible: true,
        message: 'Product added to cart!',
        type: 'success',
      });
    } catch (error) {
      setSnackbar({
        isVisible: true,
        message: 'Failed to add product to cart',
        type: 'error',
      });
    }
  };

  const closeSnackbar = () => {
    setSnackbar(prev => ({ ...prev, isVisible: false }));
  };

  if (loading) {
    return <div className="text-center">Loading products...</div>;
  }

  if (products.length === 0) {
    return (
      <div className="text-center">
        <p className="text-gray-500">No products available.</p>
        <button
          onClick={() => window.location.reload()}
          className="mt-4 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
        >
          Refresh
        </button>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      {products.map((product) => (
        <div
          key={product.id}
          className="bg-white rounded-lg shadow-md overflow-hidden border"
        >
          {product.image && (
            <img
              src={product.image}
              alt={product.name}
              className="w-full h-48 object-cover"
            />
          )}
          <div className="p-4">
            <h3 className="font-semibold text-lg mb-2">{product.name}</h3>
            <p className="text-gray-600 text-sm mb-2">
              {product.description}
            </p>
            <div className="flex items-center justify-between">
              <span className="text-2xl font-bold text-green-600">
                ${product.price}
              </span>
              <span className="text-sm text-gray-500">
                Stock: {product.stock}
              </span>
            </div>
            <button
              onClick={() => handleAddToCart(product.id)}
              disabled={product.stock === 0}
              className="w-full mt-4 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed"
            >
              {product.stock === 0 ? 'Out of Stock' : 'Add to Cart'}
            </button>
          </div>
        </div>
      ))}
      
      <Snackbar
        message={snackbar.message}
        isVisible={snackbar.isVisible}
        onClose={closeSnackbar}
      />
    </div>
  );
}